package com.ucode.hrm.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.ucode.hrm.mapper.HrmEmployeeCostDetailMapper;
import com.ucode.hrm.mapper.HrmPaySlipMapper;
import com.ucode.hrm.service.HrmEmployeeCostDetailService;
import com.ucode.hrm.service.HrmPaySlipService;
import com.ucode.model.hrm.HrmEmployeeCostDetail;
import com.ucode.model.hrm.HrmPaySlip;
import com.ucode.model.hrm.convert.HrmPaySlipConvert;
import com.ucode.tool.util.IdentifyUtils;
import groovy.lang.Lazy;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class HrmEmployeeCostDetailServiceImpl implements HrmEmployeeCostDetailService {

    @Resource
    private HrmEmployeeCostDetailMapper hrmEmployeeCostDetailMapper;
    @Resource
    SqlSessionTemplate sqlSessionTemplate;
    @Resource
    @Lazy
    private HrmPaySlipService hrmPaySlipService;

    @Override
    public HrmEmployeeCostDetailMapper initMapper() {
        return hrmEmployeeCostDetailMapper;
    }

    @Override
    public int batchInsert(List<HrmEmployeeCostDetail> list) {
        List<String> showColumns = hrmPaySlipService.getPaySlipShowColumns();
        int i = 0;
        if(CollUtil.isNotEmpty( list)) {
            //如果自动提交设置为true,将无法控制提交的条数，改为最后统一提交
            SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
            HrmEmployeeCostDetailMapper batchMapper = sqlSession.getMapper(HrmEmployeeCostDetailMapper.class);
            HrmPaySlipMapper hrmPaySlipMapper = sqlSession.getMapper(HrmPaySlipMapper.class);
            int BATCH = 500;
            for (int index = 0; index < list.size(); index++) {
                HrmEmployeeCostDetail bean = list.get(index);
                batchMapper.insert(bean);

                //保存工资条
                HrmPaySlip hrmPaySlip = HrmPaySlipConvert.INSTANCE.convert(bean, showColumns);
                hrmPaySlip.setId(IdentifyUtils.getDefaultSnowflakeId());
                hrmPaySlipMapper.insert(hrmPaySlip);

                if (index != 0 && index % BATCH == 0) {
                    sqlSession .commit();
                }
            }
            sqlSession.commit();
        }
        return i;
    }
}
